package Compress;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
import org.apache.hadoop.io.compress.CompressionInputStream;
import org.apache.hadoop.io.compress.CompressionOutputStream;
import org.apache.hadoop.util.ReflectionUtils;

import java.io.File;
import java.io.FileInputStream;

import java.io.FileOutputStream;

public class compressTest {
    public static void main(String[] args) throws Exception{
        //实现方法alt+enter
        //压缩
        mycompress("E:\\test\\words\\word4(19.2M).txt","org.apache.hadoop.io.compress.BZip2Codec");
        //解压缩
        myDecompression("E:\\test\\words\\word4(19.2M).txt.bz2");
    }

    /**
     * 解压缩
     * @param fileName
     */
    private static void myDecompression(String fileName) throws  Exception {
        //1.创建或去Factory实例
        CompressionCodecFactory factory = new CompressionCodecFactory(new Configuration());
        CompressionCodec codec = factory.getCodec(new Path(fileName));
        //获取输入流
        FileInputStream fis = new FileInputStream(new File(fileName));
        CompressionInputStream cis = codec.createInputStream(fis);

        //获取输出流
        FileOutputStream fos = new FileOutputStream(new File(fileName + ".decode"));

        //流拷贝
        IOUtils.copyBytes(cis,fos,10*1024*1024,true);

    }

    /**
     * 压缩文件
      * @param fileName
     * @param codeType
     * @throws Exception
     */
    private static void mycompress(String fileName, String codeType) throws Exception{
        //读取文件
        //1.创建输入流
        FileInputStream fis = new FileInputStream(new File(fileName));

        //2.通过反射找到编码解码器的类
        Class<?> codeClass = Class.forName(codeType);

        //3.通过反射工具找到编码器对象(创建实例)，设置参数
        CompressionCodec codec =(CompressionCodec) ReflectionUtils.newInstance(codeClass, new Configuration());
        //4.创建输入流
        FileOutputStream fos = new FileOutputStream(new File(fileName + codec.getDefaultExtension()));
        //5.解码器输出对象
        CompressionOutputStream cos = codec.createOutputStream(fos);

        //6.流拷贝
        IOUtils.copyBytes(fis,cos,20*1024*1024,true);
    }
}
